#include "InputHandler.h"
#include "Game.h"

InputHandler * InputHandler::s_pInstance = nullptr;

InputHandler::InputHandler()
{
    for (int i = 0; i <3; i++){
        m_mouseButtonStates.push_back(false);
    }
    m_mousePosition = new Vector2D(0.0,0.0);
}

void InputHandler::initialiseJoysticks(){
    if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0){
        SDL_InitSubSystem(SDL_INIT_JOYSTICK);
    }

    if (SDL_NumJoysticks() >0){
        for (int i = 0; i < SDL_NumJoysticks(); i++){
            SDL_Joystick * joy = SDL_JoystickOpen(i);
            if (joy){
                m_joysticks.push_back(joy);
            } else {
                std::cout << SDL_GetError();
            }
        }
        SDL_JoystickEventState(SDL_ENABLE);
        m_bJoysticksInitialised = true;
        std::cout << "Initialised " << m_joysticks.size() << " joysticks(s)";
    } else {
        m_bJoysticksInitialised = false;
        std::cout << "Initialised joysticks error" << std::endl;
    }
}

bool InputHandler::isKeyDown(SDL_Scancode key){
    if (m_keystates != 0){
        if (m_keystates[key] == 1){
            return true;
        }
        return false;
    }

    return false;
}

void InputHandler::clean(){
    if (m_bJoysticksInitialised){
        for (unsigned int  i = 0; i < SDL_NumJoysticks(); i++){
            SDL_JoystickClose(m_joysticks[i]);
        }
    }
}

void InputHandler::update(){
    SDL_Event event;

    while(SDL_PollEvent(&event)){
        m_keystates = (uint8_t *)SDL_GetKeyboardState(0);

        if (event.type == SDL_QUIT){
            TheGame::Instance()->clean();
        }
        
        if (event.type == SDL_MOUSEBUTTONDOWN){
            if (event.button.button == SDL_BUTTON_LEFT){
                m_mouseButtonStates[MOUSE_LEFT] = true;
            }    
            if (event.button.button == SDL_BUTTON_MIDDLE){
                m_mouseButtonStates[MOUSE_MIDDLE] = true;
            }    
            if (event.button.button == SDL_BUTTON_RIGHT){
                m_mouseButtonStates[MOUSE_RIGHT] = true;
            }    
        }

        if (event.type == SDL_MOUSEBUTTONUP){
            if (event.button.button == SDL_BUTTON_LEFT){
                m_mouseButtonStates[MOUSE_LEFT] = false;
            }    
            if (event.button.button == SDL_BUTTON_MIDDLE){
                m_mouseButtonStates[MOUSE_MIDDLE] = false;
            }    
            if (event.button.button == SDL_BUTTON_RIGHT){
                m_mouseButtonStates[MOUSE_RIGHT] = false;
            }    
        }

        if (event.type == SDL_MOUSEMOTION){
            m_mousePosition->setX(event.motion.x);
            m_mousePosition->setY(event.motion.y);
        }



    }

}
